package com.shanzhu.volunteer.modules.ai.service;

import com.shanzhu.volunteer.modules.ai.dto.AIEvaluationRequestDTO;
import com.shanzhu.volunteer.modules.ai.dto.EvaluationResultDTO;
import com.shanzhu.volunteer.modules.ai.dto.RecommendationDTO;
import com.shanzhu.volunteer.modules.ai.dto.StudentProfileDTO;
import com.shanzhu.volunteer.persistent.dataobject.CeStudent;
import com.shanzhu.volunteer.persistent.repository.ICeStudentRepo;
import com.shanzhu.volunteer.persistent.dataobject.CeTagRel;
import com.shanzhu.volunteer.persistent.repository.ICeTagRelRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * AI模型服务
 */
@Service
public class AIModelService {
    private static final Logger logger = LoggerFactory.getLogger(AIModelService.class);
    
    @Autowired
    private XGBoostModelService xgBoostModelService;
    
    @Autowired
    private MatchingAlgorithm matchingAlgorithm;
    
    @Autowired
    private SummaryGenerator summaryGenerator;
    
    @Autowired(required = false)
    private ICeStudentRepo studentRepo;
    
    @Autowired(required = false)
    private ICeTagRelRepo tagRelRepo;
    
    /**
     * 分析学生档案
     *
     * @param request AI分析请求
     * @return 分析结果
     */
    public EvaluationResultDTO analyzeStudentProfile(AIEvaluationRequestDTO request) {
        logger.info("开始分析学生档案，学号：{}", request.getStudentNo());
        
        try {
            // 1. 获取学生信息
            StudentProfileDTO studentProfile = getStudentProfile(request.getStudentNo());
            if (studentProfile == null) {
                logger.warn("未找到学号为 {} 的学生信息", request.getStudentNo());
                return generateFallbackResult(request, "未找到学生信息");
            }
            
            // 2. 提取学生特征
            Map<String, Object> studentFeatures = extractStudentFeatures(studentProfile);
            
            // 3. 计算匹配度
            List<RecommendationDTO> recommendations = matchingAlgorithm.calculateMatches(
                studentFeatures,
                request.getDimensions(),
                request.getCount()
            );
            
            // 4. 生成分析摘要
            String summary = summaryGenerator.generateSummary(studentFeatures, recommendations);
            
            // 5. 生成专家建议
            String expertAdvice = summaryGenerator.generateExpertAdvice(studentFeatures, recommendations);
            
            // 6. 计算维度匹配分数
            Map<String, List<Integer>> dimensionScores = calculateDimensionScores(
                recommendations, 
                request.getDimensions()
            );
            
            // 7. 构建分析结果
            EvaluationResultDTO result = new EvaluationResultDTO();
            result.setStudentProfile(studentProfile);
            result.setSummary(summary);
            result.setRecommendations(recommendations);
            result.setMatchingScores(dimensionScores);
            result.setExpertAdvice(expertAdvice);
            
            logger.info("学生档案分析完成，推荐数量：{}", recommendations.size());
            return result;
            
        } catch (Exception e) {
            logger.error("分析学生档案出错", e);
            return generateFallbackResult(request, "分析过程中发生错误");
        }
    }
    
    /**
     * 获取学生信息
     */
    private StudentProfileDTO getStudentProfile(String studentNo) {
        if (studentRepo == null) {
            logger.warn("学生仓库未注入，无法获取真实学生信息，返回模拟数据。");
            return createMockStudentProfile(studentNo);
        }

        try {
            CeStudent student = studentRepo.selectStudentByNo(studentNo);

            if (student == null) {
                return null;
            }

            StudentProfileDTO profile = new StudentProfileDTO();
            profile.setId(student.getId());
            profile.setStudentNo(student.getStudentNo());
            profile.setStudentName(student.getStudentName());
            profile.setGrade(student.getGrade());
            profile.setScore(student.getAchievement());
            profile.setRank(student.getRank());

            if (tagRelRepo != null) {
                // 假设 tagRelRepo 有根据学生ID查询标签关系的方法
                // List<CeTagRel> tags = tagRelRepo.selectTagsByStudentId(student.getId());
                // String tagNames = tags.stream().map(CeTagRel::getTagName).collect(Collectors.joining(","));
                // profile.setTagNameText(tagNames);
                // --- 占位符 ---
                profile.setTagNameText("模拟标签1,模拟标签2");
            } else {
                logger.warn("标签仓库未注入，无法获取学生标签。");
                profile.setTagNameText("未知标签");
            }

            return profile;

        } catch (Exception e) {
            logger.error("从数据库获取学生信息时出错，学号: {}", studentNo, e);
            return createMockStudentProfile(studentNo);
        }
    }
    
    /**
     * 创建模拟学生信息 (用于仓库未注入或查询失败时)
     */
    private StudentProfileDTO createMockStudentProfile(String studentNo) {
        StudentProfileDTO profile = new StudentProfileDTO();
        profile.setId(Math.abs(studentNo.hashCode()) % 1000L);
        profile.setStudentNo(studentNo);
        profile.setStudentName("模拟学生");
        profile.setGrade("模拟高三");
        
        int hashCode = Math.abs(studentNo.hashCode());
        int score = 500 + hashCode % 200;
        int rank = 3000 - score;
        
        profile.setScore(score);
        profile.setRank(rank);
        profile.setTagNameText("模拟理科,模拟爱好者");
        return profile;
    }
    
    /**
     * 提取学生特征
     */
    private Map<String, Object> extractStudentFeatures(StudentProfileDTO profile) {
        Map<String, Object> features = new HashMap<>();
        
        features.put("studentNo", profile.getStudentNo());
        features.put("score", profile.getScore());
        features.put("rank", profile.getRank());
        
        if (profile.getTagNameText() != null) {
            features.put("tags", Arrays.asList(profile.getTagNameText().split(",")));
        }
        
        return features;
    }
    
    /**
     * 计算各维度的匹配分数
     */
    private Map<String, List<Integer>> calculateDimensionScores(
            List<RecommendationDTO> recommendations,
            List<String> dimensions) {
        
        Map<String, List<Integer>> dimensionScores = new HashMap<>();
        
        Map<String, String> dimensionLabels = new HashMap<>();
        dimensionLabels.put("interest", "学科兴趣");
        dimensionLabels.put("career", "就业前景");
        dimensionLabels.put("environment", "院校环境");
        dimensionLabels.put("potential", "专业潜力");
        dimensionLabels.put("personality", "性格匹配");
        
        if (recommendations == null || recommendations.isEmpty()) {
            return dimensionScores;
        }
        
        for (String dimension : dimensions) {
            String label = dimensionLabels.getOrDefault(dimension, dimension);
            List<Integer> scores = new ArrayList<>();
            
            for (RecommendationDTO rec : recommendations) {
                int score = (int) Math.round(rec.getMatchScore());
                
                if ("interest".equals(dimension) && rec.getMajorName() != null && rec.getMajorName().contains("计算机")) {
                    score = Math.min(100, score + 5);
                } else if ("career".equals(dimension) && rec.getCollegeName() != null && (rec.getCollegeName().contains("清华") || rec.getCollegeName().contains("北京"))) {
                    score = Math.min(100, score + 8);
                }
                scores.add(Math.max(0, Math.min(100, score)));
            }
            dimensionScores.put(label, scores);
        }
        
        return dimensionScores;
    }
    
    /**
     * 生成备选结果（当分析失败时使用）
     */
    private EvaluationResultDTO generateFallbackResult(AIEvaluationRequestDTO request, String errorMessage) {
        logger.warn("生成备选结果，原因: {}", errorMessage);
        
        StudentProfileDTO studentProfile = getStudentProfile(request.getStudentNo());
        if (studentProfile == null) {
            studentProfile = createMockStudentProfile(request.getStudentNo());
        }
        
        List<RecommendationDTO> recommendations = matchingAlgorithm.calculateMatches(
            extractStudentFeatures(studentProfile),
            Arrays.asList("interest", "career"),
            request.getCount() > 0 ? request.getCount() : 5
        );
        
        EvaluationResultDTO result = new EvaluationResultDTO();
        result.setStudentProfile(studentProfile);
        result.setSummary("AI分析未完成: " + errorMessage + "。根据学生基本资料，初步建议关注综合性大学或理工类院校。");
        result.setRecommendations(recommendations);
        result.setMatchingScores(new HashMap<>());
        result.setExpertAdvice("由于分析出错(" + errorMessage + ")，无法提供详细专家建议。请检查输入或稍后重试。");
        
        return result;
    }
}